import { _decorator, Component, Label, Node, resources, Sprite, SpriteFrame, Texture2D, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Tile')
export class Tile extends Component {

    /**
     * 显示的值
     */
    @property(Label)
    label: Label = null;

    /**
     * 背景
     */
    @property(Sprite)
    bg: Sprite = null;

    static readonly moveTime: number = 0.3;
    static readonly createTime: number = 0.2;

    /**
     * Map 数字对应bg资源, key: 数字, value: 资源名 string
     */
    private bgMap: { [key: number]: string } = {
        0: '0',
        2: '2',
        4: '4',
        8: '8',
        16: '16',
        32: '32',
        64: '64',
        128: '128',
        256: '256',
        512: '512',
        1024: '1024',
        2048: '2048',
        4096: '4096',
    }

    start() {

    }

    update(deltaTime: number) {

    }

    /**
     * 
     * @param value 设置值
     */
    setValue(value: number) {
        if (value == 0) {
            this.label.string = "";
        } else {
            this.label.string = value.toString();
        }
        /**
         * 必须要加/spriteFrame后缀,要不然加载不到
         * 不能加扩展名,要不然加载不到
         */
        resources.load(this.bgMap[value] + "/spriteFrame", SpriteFrame, (err: any, spriteFrame: SpriteFrame) => {
            this.bg.spriteFrame = spriteFrame;
        });


    }

    /**
     * 初始化Tile
     * @param value 值
     * @param x 
     * @param y 
     */
    initTile(value: number, x: number, y: number) {
        this.setValue(value);
        this.playCreateAnim();
        this.node.setPosition(this.getPosition(x, y));
    }

    /**
     * 播放创建动画
     */
    playCreateAnim() {
        this.node.setScale(0, 0);
        /**
         * 
         */
        tween(this.node)
        .delay(Tile.createTime)
        .to(0.5, { scale: new Vec3(1, 1, 1) }, {
            easing: 'backOut'
        }).start();
    }

    /**
     * 输入x,y  获取位置
     */
    getPosition(x: number, y: number) {
        /**
         * 大格子 800 * 800
         * 小格式 175 * 175
         * 间隔 20
         * 开始位置是 0.5 * 175 + 20 = 107.5
         * 减去两边的间隔 800 - 20 * 2 = 760
         * 格子间间距（800 - 20 * 2） / 4 = 195
         * 
         */
        return new Vec3(x * 195 + 107.5, y * 195 + 107.5);
    }

    /**
     * 移动Tile
     * @param x 
     * @param y 
     */
    moveTile(x: number, y: number) {
        tween(this.node).to(Tile.moveTime, { position: this.getPosition(x, y) }, {
            easing: 'quadOut',
        }).start();
    }

    /**
     * 销毁Tile
     */
    destroyTile() {
        tween(this.node).delay(Tile.moveTime).call(() => {
            this.node.destroy();
        }).start();
    }

}


